var flow = null;
var initNodeIndex = 0;
function initFlow(data){
    jsPlumb.reset();
    $("#main").children().remove();
    initNodeIndex = 0;
    flow = data;
    if(flow.flowScript && flow.flowScript != ""){
        flow.flowScript = JSON.parse(flow.flowScript);
    }
    var syncCallBack = function(){
        if(flow.flowScript != null && flow.flowScript.length > 0){
            var syncNodes = $("#syncNode").children();
            $.each(syncNodes, function (index, item) {
                item = $(item);
                for(var i=0;i<flow.flowScript.length;i++){
                    if(item.attr("data-index") == flow.flowScript[i].id){

                        var div = item.prop("outerHTML");
                        $(item).addClass("theGrey").draggable("disable"); // 禁止其拖动功能

                        var ele = $(div).attr("class", "item");
                        ele.css({"left": parseFloat(flow.flowScript[i].offset.left),"top": parseFloat(flow.flowScript[i].offset.top), position: "absolute",margin:0});
                        $("#main").append(ele);
                        initNodeIndex ++;
                        if(flow.flowScript[i].id == "0"){
                            jsPlumb.addEndpoint(ele, { anchors: "BottomCenter", uuid: "start_"+flow.flowScript[i].id}, origin);//起点
                        }else if(flow.flowScript[i].id == "-1"){
                            jsPlumb.addEndpoint(ele, { anchors: "TopCenter", uuid: "end_"+flow.flowScript[i].id}, destination);//终点
                        }else{
                            jsPlumb.addEndpoint(ele, { anchors: "BottomCenter", uuid: "start_"+flow.flowScript[i].id}, origin);//起点
                            jsPlumb.addEndpoint(ele, { anchors: "TopCenter", uuid: "end_"+flow.flowScript[i].id}, destination);//终点
                        }

                        jsPlumb.draggable(ele,{containment: "parent"});// 端点可以拖动设置,并且将端点限制在父级内
                        $(ele).draggable({ // 设置拖动到main区域中的元素还可以拖拽
                            containment: "parent" // 限制拖动不超过父级边框
                        });
                    }
                }
            });
            if(initNodeIndex > 1 && initNodeIndex == flow.flowScript.length){
                $.each(flow.flowScript, function(index, item){
                    if(index < flow.flowScript.length - 1){
                        jsPlumb.connect({ uuids: ["start_"+item.id, 'end_' + flow.flowScript[index+1].id] });
                    }
                });
            }
        }
    };
    var developCallBack = function(){
        if(flow.flowScript != null && flow.flowScript.length > 0){
            var syncNodes = $("#developNode").children();
            $.each(syncNodes, function (index, item) {
                item = $(item);
                for(var i=0;i<flow.flowScript.length;i++){
                    if(item.attr("data-index") == flow.flowScript[i].id){

                        var div = item.prop("outerHTML");
                        $(item).addClass("theGrey").draggable("disable"); // 禁止其拖动功能

                        var ele = $(div).attr("class", "item");
                        ele.css({"left": parseFloat(flow.flowScript[i].offset.left),"top": parseFloat(flow.flowScript[i].offset.top), position: "absolute",margin:0});
                        $("#main").append(ele);
                        initNodeIndex ++;
                        if(flow.flowScript[i].id == "0"){
                            jsPlumb.addEndpoint(ele, { anchors: "BottomCenter", uuid: "start_"+flow.flowScript[i].id}, origin);//起点
                        }else if(flow.flowScript[i].id == "-1"){
                            jsPlumb.addEndpoint(ele, { anchors: "TopCenter", uuid: "end_"+flow.flowScript[i].id}, destination);//终点
                        }else{
                            jsPlumb.addEndpoint(ele, { anchors: "BottomCenter", uuid: "start_"+flow.flowScript[i].id}, origin);//起点
                            jsPlumb.addEndpoint(ele, { anchors: "TopCenter", uuid: "end_"+flow.flowScript[i].id}, destination);//终点
                        }

                        jsPlumb.draggable(ele,{containment: "parent"});// 端点可以拖动设置,并且将端点限制在父级内
                        $(ele).draggable({ // 设置拖动到main区域中的元素还可以拖拽
                            containment: "parent" // 限制拖动不超过父级边框
                        });
                    }
                }
            });
            if(initNodeIndex > 1 && initNodeIndex == flow.flowScript.length){
                $.each(flow.flowScript, function(index, item){
                    if(index < flow.flowScript.length - 1){
                        jsPlumb.connect({ uuids: ["start_"+item.id, 'end_' + flow.flowScript[index+1].id] });
                    }
                });
            }
        }
    };
    initSync(syncCallBack);
    initDevelop(developCallBack);
}

function initSync(callback){
    $("#syncNode").html("");
    $("#syncNode").append('<div class="item" style="background: #96f383" data-index="0">开始</div>');
    $.ajax({
        type: "POST",
        url: baseURL + 'dataworks/sync/list',
        header: {limit: 100000},
        data: {'spaceId': getCookie("user_space_id")},
        success: function(r){
            if(r.code === 0){
                $.each(r.data.data, function(index, item){
                    $("#syncNode").append('<div class="item" data-type="1" data-index="'+item.id+'">'+item.name+'</div>');
                });
                $("#syncNode").children().draggable({
                    helper: "clone",
                    scope: "ss",
                });

                if(callback){
                    callback();
                }
            }else{
                alert(r.msg);
            }
        }
    });
}
function initDevelop(callback){
    $("#developNode").html("");
    $("#developNode").append('<div class="item" style="background: #fa9797" data-index="-1">结束</div>');
    $.ajax({
        type: "POST",
        url: baseURL + 'dataworks/develop/list',
        header: {limit: 100000},
        data: {'spaceId': getCookie("user_space_id")},
        success: function(r){
            if(r.code === 0){
                $.each(r.data.data, function(index, item){
                    $("#developNode").append('<div class="item" data-type="2" data-index="'+item.id+'">'+item.name+'</div>');
                });
                $("#developNode").children().draggable({
                    helper: "clone",
                    scope: "ss",
                });

                if(callback){
                    callback();
                }
            }else{
                alert(r.msg);
            }
        }
    });
}
function deepCopy(p, c) {  //克隆对象
    var c = c || {};
    for (var i in p) {
        if(! p.hasOwnProperty(i)){
            continue;
        }
        if (typeof p[i] === 'object') {
            c[i] = (p[i].constructor === Array) ? [] : {};
            deepCopy(p[i], c[i]);
        } else {
            c[i] = p[i];
        }
    }
    return c;
}
function buildFlowScript(isSubmit) {
    var connects = [];//存储连线的数组
    var mainArr=[];//存储元素的数组
    var isStart = false;
    var isEnd = false;
    $.each(jsPlumb.getAllConnections(), function (idx, connection) {
        if($(connection.source).attr("data-index") == 0){
            isStart = true;
        }
        if($(connection.target).attr("data-index") == -1){
            isEnd = true;
        }
        connects.push({
            ConnectionId: connection.id,
            start:$(connection.source).attr("data-index"),
            end:$(connection.target).attr("data-index"),
            originSign:$(connection.source).attr("data-sign"),
            destinationSign:$(connection.target).attr("data-sign"),
        });
    });
    $("#main .item").each(function(){
        mainArr.push({
            offset:$(this).position(),
            name:$(this).text(),
            id:$(this).attr("data-index"),
            type: $(this).attr("data-type")
        });
    });
    // 判断起始节点
    if(!isStart){
        alert("未连线【开始】节点！");
        return null;
    }
    // 判断结束节点
    if(!isEnd){
        alert("未连线【结束】节点！");
        return null;
    }
    // 判断闭环 + 排序
    var sortArray = [];
    var isClose = findEnd(connects, "0", sortArray, mainArr);
    if(!isClose){
        alert("开始到结束节点连线未闭环！");
        return null;
    }
    if(isSubmit){
        $.ajax({
            type: "POST",
            url: baseURL + "dataworks/flow/saveFlowScript?id=" + flow.id,
            contentType: "application/json",
            data: JSON.stringify(sortArray),
            success: function(r){
                alert(r.msg);
            }
        });
    }
    return JSON.stringify(sortArray);
}
function findEnd(arr, index, sortArray, mainArr){
    for(var i=0;i<arr.length; i++){
        if(arr[i].start == index){
            sortArray.push(findItem(mainArr, index));
            if(arr[i].end == "-1"){
                sortArray.push(findItem(mainArr, arr[i].end));
                return true;
            }else{
                return findEnd(arr, arr[i].end, sortArray, mainArr);
            }
        }
    }
    return false;
}
function findItem(mainArr, index){
    for(var i=0; i<mainArr.length; i++){
        if(mainArr[i].id == index){
            return mainArr[i];
        }
    }
    return null;
}
$(function(){
    readyJsPlumb();
});

var connectorPaintStyle = {//基本连接线样式
    lineWidth: 1,
    strokeStyle: '#4caf50',
    joinstyle: 'round',
    fill: 'pink',
    outlineColor: '',
    outlineWidth: ''
};
var connectorHoverStyle = {// 鼠标悬浮在连接线上的样式
    lineWidth: 3,
    strokeStyle: '#4caf50',
    joinstyle: 'round',
    fill: 'pink',
    outlineColor: '',
    outlineWidth: ''
};
var origin = {//起点
    endpoint: ["Dot", { radius: 8 }],  //端点的形状
    connectorStyle: connectorPaintStyle,//连接线的颜色，大小样式
    connectorHoverStyle: connectorHoverStyle,
    paintStyle: {
        strokeStyle: "#989898",
        fillStyle: "transparent",
        radius: 4,
        lineWidth: 1
    },        //端点的颜色样式
//                    anchor: "AutoDefault",
    isSource: true,    //是否可以拖动（作为连线起点）
    connector: ['Straight', {
        gap: 0,
        cornerRadius: 5,
        alwaysRespectStubs: true
    }], // 连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
    isTarget: false,    //是否可以放置（连线终点）
    maxConnections: 1,    // 设置连接点最多可以连接几条线,-1表示无限大
    connectorOverlays: [["Arrow", { width: 10, length: 10, location: 1 }]]
};
var destination = {//终点
    endpoint: ["Dot", { radius: 5 }],  //端点的形状
    connectorStyle: connectorPaintStyle,//连接线的颜色，大小样式
    connectorHoverStyle: connectorHoverStyle,
    paintStyle: {fillStyle: "#989898",},        //端点的颜色样式
    isSource: false,    //是否可以拖动（作为连线起点）
    connector: ["Bezier", { stub: [40, 60], gap: 10, cornerRadius: 5, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
    isTarget:true,    //是否可以放置（连线终点）
    maxConnections: 1,    // 设置连接点最多可以连接几条线,-1表示无限大
    connectorOverlays: [["Arrow", { width: 10, length: 10, location: 1 }]]
};

function readyJsPlumb(){
    jsPlumb.ready(function() {
        var elementSign=0;//标志元素唯一性
        $("#main").droppable({
            scope: "ss",
            drop: function (event, ui) {//在目标(target)容器上释放鼠标 ,ui.draggable[0]为开始拖拽的元素
                elementSign++;
                var left = parseInt(ui.offset.left - $(this).offset().left);
                var top = parseInt(ui.offset.top - $(this).offset().top);
                var obj = ui.draggable[0].outerHTML;
                var ele = $(obj).attr("class", "item").attr("data-index", $(ui.draggable[0]).attr("data-index"));
                ele.css({"left":left,"top":top,position: "absolute",margin:0});
                $(this).append(ele);
                if($(ui.draggable[0]).attr("data-index") == "0"){
                    jsPlumb.addEndpoint(ele, { anchors: "BottomCenter" }, origin);//起点
                }else if($(ui.draggable[0]).attr("data-index") == "-1"){
                    jsPlumb.addEndpoint(ele, { anchors: "TopCenter" }, destination);//终点
                }else{
                    jsPlumb.addEndpoint(ele, { anchors: "BottomCenter" }, origin);//起点
                    jsPlumb.addEndpoint(ele, { anchors: "TopCenter" }, destination);//终点
                }

                jsPlumb.draggable(ele,{containment: "parent"});// 端点可以拖动设置,并且将端点限制在父级内
                $(ele).draggable({ //设置拖动到main区域中的元素还可以拖拽
                    containment: "parent" //限制拖动不超过父级边框
                });
                //禁止重复拖拽
                $(ui.draggable[0]).addClass("theGrey").draggable("disable"); // 禁止其拖动功能
            }
        });
        $("#main").on("mouseenter", ".item", function () {
            var ele=$('<span>X</span>');
            ele.css({position:"absolute",left:"105px",top:"0px"});
            $(this).append(ele);
        }).on("mouseleave", ".item", function () {
            $("span").remove();
        }).on("click", "span",function () {
            if (confirm("确定删除吗?")) {
                jsPlumb.removeAllEndpoints($(this).parent().attr("id"));
                var index=$(this).parent().attr("data-index");
                $(this).parent().remove();
                $(".node .item").each(function(){
                    if($(this).attr("data-index")==index){
                        $(this).removeClass("theGrey").draggable("enable"); // 激活其拖动功能
                    }
                });
            }
        });
        jsPlumb.bind("click", function (conn, originalEvent) {//点击线段删除
            if ((conn.target && conn.source) && confirm("确定删除吗?")){
                jsPlumb.detach(conn);
            }
        });
        jsPlumb.bind("connection", function (connInfo, originalEvent) {//自己连自己管控
            if (connInfo.connection.sourceId == connInfo.connection.targetId) {
                alert("不能连接自己！");
                setTimeout(function(){
                    jsPlumb.detach(connInfo.connection);
                },100);
            }
        });
        // if(sessionStorage.getItem("flowsheet")){//判断是否有保存过
        //     var flowsheet=JSON.parse(sessionStorage.getItem("flowsheet"));
        //     var mainHTML=""
        //     for(var i=0;i<flowsheet.mainArr.length;i++){
        //         if(elementSign<flowsheet.mainArr[i].sign){//如果已经保存过,即将标记更新
        //             elementSign=flowsheet.mainArr[i].sign;
        //         }
        //         mainHTML+='<div class="item" data-sign="'+flowsheet.mainArr[i].sign+'"  data-index="'+flowsheet.mainArr[i].index+'" style="left:'+flowsheet.mainArr[i].offset.left+'px;top:'+flowsheet.mainArr[i].offset.top+'px;position:absolute;margin:0" >' + flowsheet.mainArr[i].text + '</div>';
        //     };
        //     $("#main").append(mainHTML);
        //     $("#main .item").each(function(){
        //         jsPlumb.addEndpoint(this, { anchors: "BottomCenter" }, deepCopy(origin, {uuid:$(this).attr("data-sign")+"origin"}));//起点
        //         jsPlumb.addEndpoint(this, { anchors: "TopCenter" },  deepCopy(destination, {uuid:$(this).attr("data-sign")+"destination"}));//终点
        //         jsPlumb.draggable(this,{containment: "parent"});//端点可以拖动设置,并且将端点限制在父级内
        //         $(this).draggable({ //设置拖动到main区域中的元素还可以拖拽
        //             containment: "parent" //限制拖动不超过父级边框
        //         });
        //     });
        //     //固定连线
        //     for(var i=0;i<flowsheet.connects.length;i++){
        //         jsPlumb.connect({uuids:[flowsheet.connects[i].originSign+"origin",flowsheet.connects[i].destinationSign+"destination"]});
        //     };
        // }
    });
}